# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
from .settings import MYSQL_DATA


class AllJdPipeline:
    conn = None

    def open_spider(self, spider):
        self.conn = pymysql.Connect(host=MYSQL_DATA['host'], user=MYSQL_DATA['user'], port=MYSQL_DATA['port'],
                                    password=MYSQL_DATA['password'], db=MYSQL_DATA['db_name'],
                                    charset='utf8')
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        title = item['title']
        price = item['price']
        shop = item['shop']
        commentCount = item['commentCount']
        goodCount = item['goodCount']
        poorCount = item['poorCount']
        goodRateShow = item['goodRateShow']
        sql = 'insert into myjd_jd(title,price,shop,commentCount,goodCount,poorCount,goodRateShow) value ("%s","%s","%s","%s","%s","%s","%s")' % (
            title, price, shop, commentCount, goodCount, poorCount, goodRateShow)
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
            print(e)
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()


class FilePipeline:
    fp = None

    def open_spider(self, spider):
        self.fp = open('./京东电脑信息1.csv', 'w+', encoding='utf8')

    def process_item(self, item, spider):
        title = item['title'].replace("\n", "").replace("\t", "").replace("(", "+").replace(")", "+")
        price = item['price']
        shop = item['shop']
        commentCount = item['commentCount']
        goodCount = item['goodCount']
        poorCount = item['poorCount']
        goodRateShow = item['goodRateShow'].strip("\n")
        data = f'{title}|{price}|{shop}|{commentCount}|{goodCount}|{poorCount}|{goodRateShow}|\n'
        print(data)
        self.fp.write(data)
        self.fp.flush()
        return item

    def close_spider(self, spider):
        self.fp.close()
